function getDistance(latlng1, latlng2) {
	let lat1 = latlng1.latitude
	let lng1 = latlng1.longitude
	let lat2 = latlng2.latitude
	let lng2 = latlng2.longitude
	var radLat1 = (lat1 * Math.PI) / 180.0
	var radLat2 = (lat2 * Math.PI) / 180.0
	var a = radLat1 - radLat2
	var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math
		.sin(b / 2), 2)))
	s = s * 6378.137 // EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000
	if (s < 1) {
		return Math.round(s * 1000) / 1 + '米'
	} else {
		return s + '千米'
	}
}

function isObject(item) {
	return (item && typeof item === 'object' && !Array.isArray(item))
}

// 防止处理多次点击
function noMultipleClicks(methods, info) {
	// methods是需要点击后需要执行的函数， info是点击需要传的参数
	let that = this
	if (that.noClick) {
		// 第一次点击
		that.noClick = false
		if (info && info !== '') {
			// info是执行函数需要传的参数
			methods(info)
		} else {
			methods()
		}
		setTimeout(() => {
			that.noClick = true
		}, 2000)
	} else {
		// 这里是重复点击的判断
	}
}

function mergeDeep(target, source) {
	let output = Object.assign({}, target)
	if (isObject(target) && isObject(source)) {
		Object.keys(source).forEach(key => {
			if (isObject(source[key])) {
				if (!(key in target))
					Object.assign(output, {
						[key]: source[key]
					})
				else
					output[key] = mergeDeep(target[key], source[key])
			} else {
				Object.assign(output, {
					[key]: source[key]
				})
			}
		})
	}
	return output
}

function addMinutes(minutes, time) {
	let now = new Date()
	now.setMinutes(now.getMinutes() + minutes)
	return formatDateTime(now, time)
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatDateTime(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	if (!date) {
		return ''
	}
	if (typeof(date) === 'number') {
		date = new Date(date * 1000)
	}
	var o = {
		'M+': date.getMonth() + 1, //月份
		'd+': date.getDate(), //日
		'h+': date.getHours(), //小时
		'm+': date.getMinutes(), //分
		's+': date.getSeconds(), //秒
		'q+': Math.floor((date.getMonth() + 3) / 3), //季度
		'S': date.getMilliseconds() //毫秒
	}
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	for (var k in o)
		if (new RegExp('(' + k + ')').test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
	return fmt
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = ''
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前'
				break
			}
		}
		return humanize || '刚刚'
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime()
		if (diff < this.UNITS['天']) {
			return this.humanize(diff)
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number)
		}
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes())
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/)
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5])
	}
}

function debounce(callback, delay = 300) {
	let timer
	let context
	return function(...arg) {
		context = this
		clearTimeout(timer)
		timer = setTimeout(() => {
			callback.apply(context, arg)
		}, delay)
	}
}

function uuid() {
	var s = []
	var hexDigits = '0123456789abcdef'
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
	}
	s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = '-'

	var uuid = s.join('')
	// console.log(uuid);
	return uuid
}
/** JS 深度克隆
 * @param value 需要克隆的值
 */
function deepClone(value) {
	// 排除原始类型的情况，函数时也满足此条件
	if (typeof value !== 'object' || value === null) {
		return value
	}
	// 克隆结果：1.数组 2.普通对象
	const result = Array.isArray(value) ? [] : {}
	// 设置克隆结果的原型链为 value 的原型链(即保持原型一致)
	Object.setPrototypeOf(result, Object.getPrototypeOf(value))
	// 浅层克隆
	for (const key in value) {
		// 排除原型上的属性
		if (Object.prototype.hasOwnProperty.call(value, key)) {
			result[key] = deepClone(value[key]) // 针对这个对象的每一个属性值进行克隆，则达到深度克隆效果
		}
	}
	return result
}

function generateFirstTextImg(width = 50,
	height = 50) {
	const dpr = uni.getWindowInfo().pixelRatio
	let canvas = uni.createOffscreenCanvas({
		type: '2d',
		width: width * dpr,
		height: height * dpr
	})
	let content = canvas.getContext('2d')

	const colorArr = ['#2c9dd4', '#7b5ae4', '#3ac280', '#ee9d44', '#ed4a4f', '#92ed46', '#ed7a16', '#ed05c7', '#fbbd08',
		'#8dc63f', '#1cbbb4', '#e03a61', '#bc824f', '#3f8e52', '#ac87bc', '#9cbc93', '#91aebc'
	]
	return {
		reset,
		genrateUrl,
		genrateColor
	}

	function reset() {
		content = null
		canvas = null
	}

	function genrateColor(i) {
		return colorArr[i]
	}

	function genrateUrl(options) {
		const {
			text = '', fontsize = 200, color = 'rgba(255,255,255,0.4)'
		} = options
		let firstText = text.slice(0, 1)
		content.clearRect(0, 0, canvas.width, canvas.height)
		content.fillStyle = color
		content.textAlign = 'center'
		content.font = fontsize + 'px "微软雅黑"'
		content.shadowBlur = 3
		content.fillText(firstText, canvas.width / 2, canvas.height / 2)
		const dataurl = canvas.toDataURL('image/png')
		return dataurl
	}
}
/** @param baseUrl url
 * @param obj
 * @returns {string}
 * eg:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
function setObjToUrlParams(baseUrl, obj) {
	let parameters = ''
	for (const key in obj) {
		parameters += key + '=' + encodeURIComponent(obj[key]) + '&'
	}
	parameters = parameters.replace(/&$/, '')
	return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters
}

const DEFAULT_CONFIG = {
	id: 'id',
	children: 'children',
	pid: 'pid',
}

// 获取配置。  Object.assign 从一个或多个源对象复制到目标对象
const getConfig = (config) => Object.assign({}, DEFAULT_CONFIG, config)
// 平面转树
function listToTree(list, config) {
	const conf = getConfig(config)
	const nodeMap = new Map()
	const result = []
	const {
		id,
		children,
		pid
	} = conf
	for (const node of list) {
		node[children] = node[children] || []
		nodeMap.set(node[id], node)
	}
	for (const node of list) {
		const parent = nodeMap.get(node[pid]);
		(parent ? parent[children] : result).push(node)
	}
	return result
}
let result = null

function findNode(list, filed, value) {
	list.forEach(item => {
		if (item[filed] === value) {
			result = item
		} else {
			if (item.children && item.children.length) {
				findNode(item.children, filed, value)
			}
		}
	})
	return result
}

function throttle(func, delay = 100) {
	let timerId = null
	return function(...args) {
		if (!timerId) {
			timerId = setTimeout(() => {
				func.apply(this, args)
				timerId = null
			}, delay)
		}
	}
}

export {
	deepClone,
	throttle,
	uuid,
	debounce,
	formatTime,
	formatDateTime,
	formatLocation,
	dateUtils,
	addMinutes,
	mergeDeep,
	getDistance,
	noMultipleClicks, //禁止多次点击
	generateFirstTextImg,
	setObjToUrlParams,
	isObject,
	listToTree,
	findNode

}